<template>
	<view class="page-cont" :style="themeStore.theme">
		<view class="nav-cont">
			<image class="nav-bg" src="/static/coldroom_background.png"></image>
			<image class="nav-back" :style="{top: statusBarHeight}" src="/static/back_arrow.png" @click="handleBack"></image>
			<view class="nav-box">
				<view class="nav-left">
					<view class="nav-room" @click="handleOpen">
						<view class="nav-room-name">{{deviceName}}</view>
						<image class="nav-room-arrow" src="/static/down_arrow.png" :style="{ transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)' }"></image>
					</view>
					<view class="nav-stat" v-if="projectType == 20">
						<view class="nav-stat-temp" v-if="statData.isTemp">
							<view class="nav-stat-temp-num">{{statData.temp}}</view>
							<view class="nav-stat-temp-unit">
								<view>°C</view>
								<view>温度</view>
							</view>
						</view>
						<image v-if="statData.isTemp" class="nav-stat-setting" src="/static/coldroom_temp.png" @click="handleSetting"></image>
						<view v-if="statData.isHum" class="nav-stat-temp">
							<view class="nav-stat-temp-num">{{statData.hum}}</view>
							<view class="nav-stat-temp-unit">
								<view>%</view>
								<view>湿度</view>
							</view>
						</view>
					</view>
					<view class="nav-status" v-if="projectType == 20 && statData.isDif">
						<view class="nav-status-item">
							<view class="nav-status-item-name">化霜</view>
							<image class="nav-status-item-logo" src="/static/frost.png"></image>
						</view>
					</view>
				</view>
				<view class="nav-right">
					<image class="nav-right-logo" src="/static/coldroom.png"></image>
				</view>
			</view>
		</view>
		<!-- tab栏 -->
		<tab class="tab-cont" :tabActive="tabActive" :tabs="tabs" :badges="badges" @tabChange="handleTabChange"></tab>
		<scroll-view class="device-list" scroll-y enable-flex refresher-enabled :refresher-triggered="isRefresh" @refresherrefresh="handlePullDownRefresh">
			<view :class="['device-item', item.alarm ? 'device-item-alarm' : '']" v-for="(item, index) in facilityList" :key="index"  @click="handleDetailClick(item)">
				<view class="device-item-status">
					<image class="device-item-status-logo" src="/static/fan_gray.png"></image>
					<view class="device-item-status-text">{{item.statusText}}</view>
					<image class="device-item-arrow" src="/static/right_arrow.png"></image>
				</view>
				<view class="device-item-name">{{item.name}}</view>
				<!-- 风机 -->
				<view class="device-item-box" v-if="deviceType == 26">
					<view class="device-item-box-left">
						<view class="device-item-box-num">{{item.diftime}}</view>
						<view class="device-item-box-name">化霜累计</view>
					</view>
					<view class="device-item-box-right">
						<view class="device-item-box-num">{{item.runtime}}</view>
						<view class="device-item-box-name">制冷累计</view>
					</view>
				</view>
				<!-- 门 -->
				<!-- <view class="device-item-box" v-if="deviceType == 24">
					<switch :checked="item.num" />
				</view> -->
				<!-- 灯组 -->
				<view class="device-item-box" v-if="deviceType == 27">
					<switch :checked="item.num" />
				</view>
				<!-- 压缩机、冷凝器  -->
				<view class="device-item-box" v-if="deviceType == 41 || deviceType == 31 || deviceType == 32">
					<view class="device-item-box-left">
						<view class="device-item-box-num">{{item.currtime}}</view>
						<view class="device-item-box-name">今日运行时间</view>
					</view>
					<view class="device-item-box-right">
						<view class="device-item-box-num">{{item.currcount}}</view>
						<view class="device-item-box-name">今日运行次数</view>
					</view>
				</view>
				<view class="device-item-box" v-if="deviceType == 41 || deviceType == 31 || deviceType == 32">
					<view class="device-item-box-left">
						<view class="device-item-box-num">{{item.sumtime}}</view>
						<view class="device-item-box-name">累计运行时间</view>
					</view>
					<view class="device-item-box-right">
						<view class="device-item-box-num">{{item.sumcount}}</view>
						<view class="device-item-box-name">累计运行次数</view>
					</view>
				</view>
				<!-- <view class="device-item-box">
					<view class="device-item-box-left">
						<view class="device-item-box-num">1</view>
						<view class="device-item-box-name">下次化霜倒计时</view>
					</view>
					<view class="device-item-box-right">
						<view class="device-item-box-num">1</view>
						<view class="device-item-box-name">膨胀阀开度</view>
					</view>
				</view> -->
				<!-- <view class="device-item-box">
					<view class="device-item-box-left">
						<view class="device-item-box-num">2</view>
						<view class="device-item-box-name">蒸发温度</view>
					</view>
					<view class="device-item-box-right">
						<view class="device-item-box-num">2</view>
						<view class="device-item-box-name">回风温度</view>
					</view>
				</view> -->
			</view>
		</scroll-view>
		<!-- 菜单按钮 -->
		<image class="menu-btn" src="/static/project-menu.png" @click="handleDrawer"></image>
	</view>
	<!-- 右侧菜单栏 -->
	<uni-drawer ref="drawerMenu" mode="right" :mask-click="true">
		<menuBar></menuBar>
	</uni-drawer>
	<!-- 弹框选择冷间 -->
	<uni-popup ref="popup" type="bottom" background-color="#fff" @maskClick="isOpen = false" :visible="isOpen">
		<scroll-view class="popup-cont" scroll-y>
			<view class="popup-header">请选择</view>
			<view class="popup-title" v-for="(item, index) in deviceList" :key="index" @click="handleDeviceChange(item)">{{ item.name }}</view>
		</scroll-view>
	</uni-popup>
</template>
<script setup lang="ts">
	import { reactive, ref, computed, onMounted, watch } from 'vue';
	import { onShow, onLoad } from '@dcloudio/uni-app';
	import { storeToRefs } from 'pinia';
	import { useNavbar } from '@/utils/hooks.js';
	import { convertHours } from '@/utils/tools.js'
	import { getProjectModel, getProjectMonitor, getProjectAlarm } from "@/api/home.js";
	import menuBar from "@/components/menu.vue";
	import useThemeStore from '@/store/theme';
	import useHomeStore from '@/store/home';
	const themeStore = useThemeStore();
	const homeStore = useHomeStore();
	const { statusBarHeight, pageHeight } = useNavbar();
	const { projectId, deviceId, deviceName, deviceType, deviceList, projectModus, projectType } = storeToRefs(homeStore);
	const drawerMenu = ref()
	const popup = ref();
	const isOpen = ref(false);
	const isRefresh = ref(false);
	const tabs = ref([]);
	const tabList = ref([])
	const badges = ref([0])
	const tabActive = ref(0)
	const statData = ref({
		temp: 0,//温度
		hum: 0,//湿度
		isTemp: false,//是否显示温度
		isHum: false,//是否显示湿度
		isDif: false,//是否显示化霜
	})
	const modusData = ref({})
	const alarmList = ref([])
	const facilityList = ref([]);//设施列表

	onLoad(() => {
		initData();
	});

	async function initData() {
		await getModelData();
		// await getAlarmData();
		getList();
		isRefresh.value = false;
	}

	// 获取项目的模块数据
	function getModelData() {
		return new Promise(resolve => {
			tabList.value = [];
			let keys = Object.keys(projectModus.value);
			if (projectType.value == '20') {
				// 冷间
				if (keys.indexOf("26") !== -1 && projectModus.value["26"].length) {
					// 风机
					tabList.value.push({ name: "风机", id: 26 });
				}
				if (keys.indexOf("27") !== -1 && projectModus.value["27"].length) {
					// 灯组
					tabList.value.push({ name: "灯组", id: 27 });
				}
				if (keys.indexOf("24") !== -1 && projectModus.value["24"].length) {
					// 门
					tabList.value.push({ name: "门", id: 24 });
				}
				// 冷间：温度21，湿度22
				statData.value.isTemp = projectModus.value["21"].length ? true : false;
				statData.value.isHum = projectModus.value["22"].length ? true : false;
				if (statData.value.isTemp) {
					// 获取冷间温度
					let datamapping = "";
					deviceList.value.forEach(element => {
						if (element.id == deviceId.value) {
							datamapping = element.datamapping;
						}
					});
					getTempData(datamapping);
				}
				if (statData.value.isHum) {
					// 获取冷间湿度
					let datamapping = "";
					deviceList.value.forEach(element => {
						if (element.id == deviceId.value) {
							datamapping = element.datamappingHum;
						}
					});
					getHumData(datamapping);
				}
			} else if (projectType.value == '40') {
				// 机组
				if (keys.indexOf("41") !== -1 && projectModus.value["41"].length) {
					// 压缩机
					tabList.value.push({ name: "压缩机", id: 41 });
				}
			} else if (projectType.value == '30') {
				// 冷凝器
				if (keys.indexOf("31") !== -1 && projectModus.value["31"].length) {
					// 水泵
					tabList.value.push({ name: "水泵", id: 31 });
				}
				if (keys.indexOf("32") !== -1 && projectModus.value["32"].length) {
					// 风机
					tabList.value.push({ name: "风机", id: 32 });
				}
			}
			tabs.value = tabList.value.map(element => {
				return element.name;
			});
			if (tabList.value.length) {
				let deviceType = tabList.value[tabActive.value].id;
				let arr = projectModus.value[deviceType];
				facilityList.value = arr.filter(element => {
					return element.pid == deviceId.value;
				});
				homeStore.setDeviceType(deviceType);//保存设备类型
				homeStore.setFacilityListList(facilityList.value); //保存设施列表
			}
			resolve(true);
		});
	}

	// 获取项目的告警数据
	function getAlarmData() {
		return new Promise(resolve => {
			if (!projectId.value) {
				resolve(false);
				return;
			}
			getProjectAlarm({ mid: projectId.value }).then(res => {
				if (res.data) {
					alarmList.value = (res.data || {})["ad"];
				}
				resolve(true);
			});
		});
	}

	// 获取设备数据
	function getList() {
		let arr = [];
		facilityList.value.forEach(element => {
			let datamapping = element.datamapping ? JSON.parse(element.datamapping || "") : [];
			if (datamapping.length) {
				if (deviceType.value == "26") {
					arr.push(datamapping[0]);
					arr.push(datamapping[1]);
				} else {
					arr.push(datamapping[0]);
				}
			}

		});
		if (!arr.length) {
			return;
		}
		getProjectMonitor({ keys: arr }).then(res => {
			// 获取预警设备的id
			let alarmIds = alarmList.value.map(element => {
				return element.oid;
			});

			let isDif = false;
			facilityList.value.forEach(element => {
				if (deviceType.value == "26") {
					// 风机：制冷、化霜、开关
					let confmapping = JSON.parse(element.confmapping);
					element.diftime = convertHours(confmapping.diftime);
					element.runtime = convertHours(confmapping.runtime);
					let key1 = `26_0_${element.id}_0`;
					let key2 = `26_0_${element.id}_1`;
					element.num1 = Number(res[key1] || 0);//制冷状态，0：关，1：开
					element.num2 = Number(res[key2] || 0);//化霜状态，0：关，1：开
					element.num = element.num1 || element.num2;
					element.statusText = element.num1 == 1 ? '制冷' : element.num2 == 1 ? '化霜' : '待机';
					isDif = element.num2 == 1 ? true : false;
				} else if (deviceType.value == "41" || deviceType.value == "31" || deviceType.value == "32") {
					// 机组：压缩机
					// 冷凝器：水泵、风机
					let confmapping = JSON.parse(element.confmapping);
					element.sumtime = convertHours(confmapping.sumtime || 0);
					element.currtime = convertHours(confmapping.currtime || 0);
					element.sumcount = confmapping.sumcount || 0;
					element.currcount = confmapping.currcount || 0;
					let key = JSON.parse(element.datamapping)[0];
					element.num = Number(res[key] || 0);
					element.statusText = element.num == 1 ? '开' : '关';
				} else {
					// 灯、门：只有开关
					let key = JSON.parse(element.datamapping)[0];
					element.num = Number(res[key] || 0);
					element.statusText = element.num == 1 ? '开' : '关';
				}

				// 判断当前设备是否预警
				if (alarmIds.indexOf(element.id) !== -1) {
					element.alarm = true;
				} else {
					element.alarm = false;
				}
			});
			statData.value.isDif = isDif;//是否存在化霜的设备
		});
	}
	// 获取当前冷间的温度
	function getTempData(key) {
		getProjectMonitor({ keys: [key] }).then(res => {
			statData.value.temp = res[key] || 0;
		});
	}
	// 获取当前冷间的湿度
	function getHumData(key) {
		if (!key) {
			return;
		}
		getProjectMonitor({ keys: [key] }).then(res => {
			statData.value.hum = res[key] || 0;
		});
	}

	// 下拉刷新
	const handlePullDownRefresh = () => {
		isRefresh.value = true;
		initData();
	}

	// 冷间切换
	function handleOpen() {
		popup.value.open();
	}

	// 菜单栏
	function handleDrawer() {
		drawerMenu.value.open();
	}

	// 设备切换
	function handleDeviceChange(e) {
		popup.value.close();
		homeStore.setDeviceId(e.id);//保存设备id
		homeStore.setDeviceName(e.name);//保存设备名称
		initData();
	}

	// 风机、灯、门切换
	async function handleTabChange(e) {
		tabActive.value = e;
		let deviceType = tabList.value[tabActive.value].id;
		let arr = projectModus.value[deviceType];
		facilityList.value = arr.filter(element => {
			return element.pid == deviceId.value;
		});
		homeStore.setDeviceType(deviceType);//保存设备类型
		homeStore.setFacilityListList(facilityList.value); //保存设施列表
		getList();
	}

	// 温度上下限设置
	function handleSetting() {
		uni.navigateTo({
			url: '/pages/home/setting-detail',
		});
	}

	// 详情
	function handleDetailClick(e) {
		homeStore.setFacilityId(e.id);
		homeStore.setFacilityName(e.name);
		if (deviceType.value == '24' || deviceType.value == '27') {
			// 门24，灯组27
			uni.navigateTo({
				url: '/pages/home/fan-detail',
			});
			return;
		}
		uni.navigateTo({
			url: '/pages/home/fan',
		});
	}

	// 返回
	function handleBack() {
		uni.navigateBack({
			delta: 1
		});
	}
</script>
<style lang="scss" scoped>
	.page-cont {
		position: relative;
		height: 100vh;

		.nav-cont {
			position: relative;
			padding-top: 95px;
			padding-bottom: 15px;
			height: 200px;
			box-sizing: border-box;

			.nav-bg {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 200px;
				z-index: 1;
			}

			.nav-back {
				position: absolute;
				top: 50px;
				left: 10px;
				padding: 10px;
				width: 40px;
				height: 40px;
				box-sizing: border-box;
				z-index: 2;
			}

			.nav-box {
				position: relative;
				display: flex;
				align-items: center;
				z-index: 100;
			}

			.nav-left {
				padding: 0 20px;
				width: 50%;
			}

			.nav-right {
				width: 50%;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.nav-right-logo {
				width: 100px;
				height: 60px;
			}

			.nav-room {
				display: flex;
				align-items: center;
			}

			.nav-room-name {
				color: #fff;
				font-size: 18px;
				font-weight: 600;
			}

			.nav-room-arrow {
				width: 12px;
				height: 12px;
			}

			.nav-stat {
				margin-top: 10px;
				display: flex;
				align-items: center;
			}

			.nav-stat-temp {
				display: flex;
				align-items: center;
			}

			.nav-stat-setting {
				margin-left: 10px;
				margin-right: 30px;
				width: 25px;
				height: 25px;
			}

			.nav-stat-temp-num {
				color: #fff;
				font-size: 25px;
				font-weight: 600;
			}

			.nav-stat-temp-unit {
				padding-left: 5px;
				color: #fff;
				font-size: 9px;
			}

			.nav-status {
				margin-top: 15px;
				display: flex;
			}

			.nav-status-item {
				padding: 0 10px;
				height: 18px;
				display: flex;
				align-items: center;
				border-radius: 9px;
				border: 1px solid #FFFFFF;
				background: linear-gradient(180deg, rgba(236, 239, 247, 1), rgba(255, 255, 255, 1));
				box-shadow: 0px 0px 10px 0px rgba(95, 131, 249, 0.2);
			}

			.nav-status-item-name {
				color: #5F83F9;
				font-size: 13px;
			}

			.nav-status-item-logo {
				padding-left: 5px;
				width: 12px;
				height: 12px;
			}
		}

		.menu-btn {
			position: fixed;
			right: 25px;
			bottom: 37px;
			width: 50px;
			height: 50px;
		}

		.device-list {
			padding: 15px;
			height: calc(100% - 252px);
			// display: flex;
			// flex-wrap: wrap;
			box-sizing: border-box;

			.device-item {
				position: relative;
				margin-left: 15px;
				padding: 10px;
				width: calc(50% - 8px);
				display: inline-block;
				border-radius: 5px;
				background: linear-gradient(180deg, rgba(238, 240, 249, 1), #fff);
				border: 1px solid #fff;
				box-shadow: 0px 10px 20px 0px rgba(95, 131, 249, 0.1);
				box-sizing: border-box;

				&:nth-child(2n + 1) {
					margin-left: 0;
				}

				&:nth-child(n + 3) {
					margin-top: 15px;
				}

				&.device-item-alarm {
					border-color: #FC4A2E;
					background: linear-gradient(180deg, #F9F1F0, #fff);
				}
			}

			.device-item-status {
				display: flex;
			}

			.device-item-status-logo {
				width: 40px;
				height: 40px;
			}

			.device-item-status-text {
				padding-left: 10px;
				color: #8A95A0;
				font-size: 11px;
			}

			.device-item-arrow {
				position: absolute;
				top: 10px;
				right: 10px;
				width: 15px;
				height: 14px;
			}

			.device-item-name {
				margin-top: 7px;
				margin-bottom: 20px;
				color: #333;
				font-size: 13px;
				font-weight: 600;
			}

			.device-item-box {
				margin-top: 14px;
				display: flex;

				&:first-child {
					margin-top: 0;
				}
			}

			.device-item-box-left {
				width: calc(50% - 5px);
			}

			.device-item-box-right {
				margin-left: 10px;
				width: calc(50% - 5px);
			}

			.device-item-box-num {
				color: $theme-color;
				font-size: 14px;
				line-height: 1;
				font-weight: 600;
				word-break: break-all;
			}

			.device-item-box-name {
				padding-top: 5px;
				color: #8A95A0;
				font-size: 11px;
				word-break: break-all;
			}
		}
	}

	.popup-cont {
		max-height: 60vh;
		background: #fff;
		overflow: hidden;
		overflow-y: auto;

		.popup-title,
		.popup-header {
			height: 100rpx;
			line-height: 100rpx;
			color: #333;
			font-size: 28rpx;
			text-align: center;
			border-top: 2rpx solid #eee;
		}

		.popup-header {
			font-size: 32rpx;
			font-weight: 600;
		}
	}
</style>